<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="JinYan&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/blog/css/images/logo.jpg">
  
  <title>
    
      Python-3-基础语法 | SanYuanEmpire
    
  </title>
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/blog/css/style.css">
<link rel="stylesheet" href="/blog/css/plugins/gitment.css">
  <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js"></script>
  <script src="/blog/js/qrious.js"></script>
<script src="/blog/js/gitment.js"></script>
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.jpg" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/blog/">
      <div class="logo"></div>
      <span>SanYuanEmpire</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/blog/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/blog/archives/" class="item-link">Archives</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/blog/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/blog/archives/" class="menu-link">Archives</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>Python-3-基础语法</h2>
  <p class="post-date">2018-08-30</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="运行-Python"><a href="#运行-Python" class="headerlink" title="运行 Python"></a>运行 Python</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">交互式解释器</span><br><span class="line">在命令行窗口执行python后，进入 Python 的交互式解释器。exit() 或 Ctrl + D 组合键退出交互式解释器。</span><br><span class="line">命令行脚本</span><br><span class="line">在命令行窗口执行python script-file.py，以执行 Python 脚本文件。</span><br><span class="line">指定解释器</span><br><span class="line">如果在 Python 脚本文件首行输入#!/usr/bin/env python，那么可以在命令行窗口中执行/path/to/script-file.py以执行该脚本文件。</span><br><span class="line">注：该方法不支持 Windows 环境。</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="编码"><a href="#编码" class="headerlink" title="编码"></a>编码</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">默认情况下，<span class="number">3.</span>x 源码文件都是 UTF<span class="number">-8</span> 编码，字符串都是 Unicode 字符。也可以手动指定文件编码：</span><br><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line">或者</span><br><span class="line"><span class="comment"># encoding: utf-8</span></span><br><span class="line">注意: 该行标注必须位于文件第一行</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="标识符"><a href="#标识符" class="headerlink" title="标识符"></a>标识符</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">第一个字符必须是英文字母或下划线 _ 。</span><br><span class="line">标识符的其他的部分由字母、数字和下划线组成。</span><br><span class="line">标识符对大小写敏感。</span><br><span class="line">注：从 3.x 开始，非 ASCII 标识符也是允许的，但不建议。</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="保留字"><a href="#保留字" class="headerlink" title="保留字"></a>保留字</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">保留字即关键字，我们不能把它们用作任何标识符名称。Python 的标准库提供了一个 keyword 模块，可以输出当前版本的所有关键字：</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> keyword</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>keyword.kwlist</span><br><span class="line">[<span class="string">'False'</span>, <span class="string">'None'</span>, <span class="string">'True'</span>, <span class="string">'and'</span>, <span class="string">'as'</span>, <span class="string">'assert'</span>, <span class="string">'break'</span>, <span class="string">'class'</span>, <span class="string">'continue'</span>, <span class="string">'def'</span>, <span class="string">'del'</span>, <span class="string">'elif'</span>, <span class="string">'else'</span>, <span class="string">'except'</span>, <span class="string">'finally'</span>, <span class="string">'for'</span>, <span class="string">'from'</span>, <span class="string">'global'</span>, <span class="string">'if'</span>, <span class="string">'import'</span>, <span class="string">'in'</span>, <span class="string">'is'</span>, <span class="string">'lambda'</span>, <span class="string">'nonlocal'</span>, <span class="string">'not'</span>, <span class="string">'or'</span>, <span class="string">'pass'</span>, <span class="string">'raise'</span>, <span class="string">'return'</span>, <span class="string">'try'</span>, <span class="string">'while'</span>, <span class="string">'with'</span>, <span class="string">'yield'</span>]</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">单行注释采用#，多行注释采用&apos;&apos;&apos;或&quot;&quot;&quot;。</span><br><span class="line"># 这是单行注释</span><br><span class="line">&apos;&apos;&apos;</span><br><span class="line">这是多行注释</span><br><span class="line">这是多行注释</span><br><span class="line">&apos;&apos;&apos;</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">这也是多行注释</span><br><span class="line">这也是多行注释</span><br><span class="line">&quot;&quot;&quot;</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="行与缩进"><a href="#行与缩进" class="headerlink" title="行与缩进"></a>行与缩进</h1><blockquote>
<p>Python 最具特色的就是使用缩进来表示代码块，不需要使用大括号 {}。 缩进的空格数是可变的，但是同一个代码块的语句必须包含相同的缩进空格数。缩进不一致，会导致运行错误。</p>
</blockquote>
<h1 id="多行语句"><a href="#多行语句" class="headerlink" title="多行语句"></a>多行语句</h1><blockquote>
<p>Python 通常是一行写完一条语句，但如果语句很长，我们可以使用反斜杠\来实现多行语句。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">total = item_one + \</span><br><span class="line">        item_two + \</span><br><span class="line">        item_three</span><br><span class="line">在 [], &#123;&#125;, 或 () 中的多行语句，不需要使用反斜杠\。</span><br></pre></td></tr></table></figure></p>
</blockquote>
<hr>
<h1 id="空行"><a href="#空行" class="headerlink" title="空行"></a>空行</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">函数之间或类的方法之间用空行分隔，表示一段新的代码的开始。类和函数入口之间也用一行空行分隔，以突出函数入口的开始。</span><br><span class="line">空行与代码缩进不同，空行并不是 Python 语法的一部分。书写时不插入空行，Python 解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码，便于日后代码的维护或重构。</span><br><span class="line">记住：空行也是程序代码的一部分。</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="等待用户输入"><a href="#等待用户输入" class="headerlink" title="等待用户输入"></a>等待用户输入</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">input函数可以实现等待并接收命令行中的用户输入。</span><br><span class="line">content = input(<span class="string">"\n\n请输入点东西并按 Enter 键\n"</span>)</span><br><span class="line">print(content)</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="同一行写多条语句"><a href="#同一行写多条语句" class="headerlink" title="同一行写多条语句"></a>同一行写多条语句</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Python 可以在同一行中使用多条语句，语句之间使用分号;分割。</span><br><span class="line">import sys; x = &apos;hello world&apos;; sys.stdout.write(x + &apos;\n&apos;)</span><br><span class="line">多个语句构成代码组</span><br><span class="line">缩进相同的一组语句构成一个代码块，我们称之代码组。</span><br><span class="line">像if、while、def和class这样的复合语句，首行以关键字开始，以冒号:结束，该行之后的一行或多行代码构成代码组。</span><br><span class="line">我们将首行及后面的代码组称为一个子句(clause)。</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="print-输出"><a href="#print-输出" class="headerlink" title="print 输出"></a>print 输出</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">print 默认输出是换行的，如果要实现不换行需要在变量末尾加上end=&quot;&quot;或别的非换行符字符串：</span><br><span class="line">print(&apos;123&apos;) # 默认换行</span><br><span class="line">print(&apos;123&apos;, end = &quot;&quot;) # 不换行</span><br></pre></td></tr></table></figure>
<h1 id="import-与-from…import"><a href="#import-与-from…import" class="headerlink" title="import 与 from…import"></a>import 与 from…import</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">在 Python 用 import 或者 from...import 来导入相应的模块。</span><br><span class="line">将整个模块导入，格式为：import module_name</span><br><span class="line">从某个模块中导入某个函数,格式为：from module_name import func1</span><br><span class="line">从某个模块中导入多个函数,格式为：from module_name import func1, func2, func3</span><br><span class="line">将某个模块中的全部函数导入，格式为：from module_name import *</span><br></pre></td></tr></table></figure>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/blog/2018/08/30/Python-3-含义和特点/">
        <span class="nav-arrow">← </span>
        
          Python-3-含义和特点
        
      </a>
    
    
      <a class="nav-right" href="/blog/2018/08/30/Python-3-运算符/">
        
          Python-3-运算符
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#运行-Python"><span class="toc-nav-text">运行 Python</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#编码"><span class="toc-nav-text">编码</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#标识符"><span class="toc-nav-text">标识符</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#保留字"><span class="toc-nav-text">保留字</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#注释"><span class="toc-nav-text">注释</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#行与缩进"><span class="toc-nav-text">行与缩进</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#多行语句"><span class="toc-nav-text">多行语句</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#空行"><span class="toc-nav-text">空行</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#等待用户输入"><span class="toc-nav-text">等待用户输入</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#同一行写多条语句"><span class="toc-nav-text">同一行写多条语句</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#print-输出"><span class="toc-nav-text">print 输出</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#import-与-from…import"><span class="toc-nav-text">import 与 from…import</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'git@gitee.com:sanyuanempire/blog.git/2018/08/30/Python-3-基础语法/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

     // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()
        
        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })

    // qrcode
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });

    // gitment
    var gitmentConfig = "";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "Python-3-基础语法",
        owner: "",
        repo: "",
        oauth: {
          client_id: "",
          client_secret: ""
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  })();
</script>

<script>
  var disqus_shortname = '';
  
  var disqus_url = 'git@gitee.com:sanyuanempire/blog.git/2018/08/30/Python-3-基础语法/';
  
  (function(){
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//go.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  })();
</script>

    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2018 | Proudly powered by <a href="https://sanyuanempire.gitee.io/blog" target="_blank">JinYan</a>
    <br>
    Theme by <a href="https://sanyuanempire.gitee.io/blog">JinYan</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/blog/js/script.js"></script>

  </body>
</html>